<?php

namespace app\common\model\banxi\grammar;

use app\common\enums\GrammarLearnPaceEnum;
use app\common\model\common\BaseModel;
use think\model\concern\SoftDelete;

/**
 * 语法学习
 */
class GrammarLearn extends BaseModel
{
    use SoftDelete;

    protected $name = 'banxi_grammar_learn';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [
        'learnPaceCn'
    ];

    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'studentId' => 'string',
        'categoryId' => 'string',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];

    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                       ｜
    //-----------------------------------------------------------------------------------

    public function getLearnPaceCnAttr($value, $data)
    {
        $value = $value ?: ($data['learnPace'] ?? '');
        return (new GrammarLearnPaceEnum())->getDescription($value) ?? '';
    }

    //-----------------------------------------------------------------------------------
    //｜                                   处理方法                                       ｜
    //-----------------------------------------------------------------------------------


    /**
     * 根据学员ID和分类ID获取学习记录
     *
     * @param int $studentId 学员ID
     * @param int $categoryId 分类ID
     * @return array|null
     */
    public function getGrammarLearnByStudentIdAndCategoryId($studentId, $categoryId)
    {
        $learn = $this->where('studentId', $studentId)
            ->where('categoryId', $categoryId)
            ->find();

        if ($learn) {
            return $learn;
        }

        // 如果不存在学习记录，则创建一条新记录
        $data = [
            'studentId' => $studentId,
            'categoryId' => $categoryId,
            'learnPace' => GrammarLearnPaceEnum::E1, // 默认值，对应GrammarLearnPace.E1
            'lastLearnTime' => date('Y-m-d H:i:s'),
            'createTime' => time(),
            'updateTime' => time()
        ];

        $id = $this->insertGetId($data);

        if ($id) {
            return $this->where('id', $id)->find();
        }

        return null;
    }


    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------

}